/*
 * @Author: Kiro AI Assistant
 * @Date: 2025-01-10
 * @Description: 导航管理器 - 集成悬浮播放器的全局显示控制
 */

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../viewmodels/music_player_view_model.dart';
import '../services/floating_player_service.dart';
import 'app_routes.dart';

/// 导航管理器
/// 负责管理页面导航和悬浮播放器的显示控制
class NavigationManager {
  static NavigationManager? _instance;
  static NavigationManager get instance => _instance ??= NavigationManager._();
  NavigationManager._();

  /// 当前页面路由名称
  String? _currentRoute;

  /// 获取当前路由
  String? get currentRoute => _currentRoute;

  /// 设置当前路由
  void setCurrentRoute(String route) {
    _currentRoute = route;
    _updateFloatingPlayerVisibility();
  }

  /// 导航到音乐搜索页面
  static Future<void> toMusicSearch(BuildContext context) async {
    instance.setCurrentRoute(AppRoutes.musicSearch);
    await AppRoutes.toMusicSearch(context);
  }

  /// 导航到音乐播放页面
  static Future<void> toMusicPlayer(
    BuildContext context, {
    dynamic music,
    bool autoPlay = false,
  }) async {
    instance.setCurrentRoute(AppRoutes.musicPlayer);
    // 进入播放页面时隐藏悬浮播放器
    FloatingPlayerService.hideFloatingPlayer();
    await AppRoutes.toMusicPlayer(context, music: music, autoPlay: autoPlay);
  }

  /// 导航到播放列表页面
  static Future<void> toPlaylist(
    BuildContext context, {
    int initialIndex = 0,
  }) async {
    instance.setCurrentRoute(AppRoutes.playlist);
    // 进入播放列表页面时隐藏悬浮播放器
    FloatingPlayerService.hideFloatingPlayer();
    await AppRoutes.toPlaylist(context, initialIndex: initialIndex);
  }

  /// 返回上一页
  static void back(BuildContext context) {
    Navigator.of(context).pop();
    // 返回后更新悬浮播放器显示状态
    WidgetsBinding.instance.addPostFrameCallback((_) {
      instance._updateFloatingPlayerVisibility();
    });
  }

  /// 返回到首页
  static void backToHome(BuildContext context) {
    instance.setCurrentRoute(AppRoutes.home);
    AppRoutes.backToHome(context);
  }

  /// 更新悬浮播放器显示状态
  void _updateFloatingPlayerVisibility() {
    // 在播放页面和播放列表页面时隐藏悬浮播放器
    final shouldHide = _currentRoute == AppRoutes.musicPlayer ||
        _currentRoute == AppRoutes.playlist;

    if (shouldHide) {
      FloatingPlayerService.hideFloatingPlayer();
    } else {
      // 在其他页面且有播放内容时显示悬浮播放器
      _showFloatingPlayerIfNeeded();
    }
  }

  /// 如果需要则显示悬浮播放器
  void _showFloatingPlayerIfNeeded() {
    // 这里需要检查是否有播放内容
    // 由于无法直接访问 context，这个方法需要在有 context 的地方调用
  }

  /// 在有播放内容时显示悬浮播放器（需要 context）
  static void showFloatingPlayerIfNeeded(BuildContext context) {
    final musicPlayerViewModel = context.read<MusicPlayerViewModel>();

    // 只有在非播放页面且有播放内容时才显示悬浮播放器
    final shouldShow = instance._currentRoute != AppRoutes.musicPlayer &&
        instance._currentRoute != AppRoutes.playlist &&
        musicPlayerViewModel.hasCurrentTrack;

    if (shouldShow) {
      FloatingPlayerService.showFloatingPlayer(context);
    }
  }

  /// 处理页面路由变化
  static void handleRouteChange(String? routeName) {
    if (routeName != null) {
      instance.setCurrentRoute(routeName);
    }
  }
}

/// 路由观察器 - 用于监听路由变化
class NavigationRouteObserver extends RouteObserver<PageRoute<dynamic>> {
  @override
  void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
    super.didPush(route, previousRoute);
    if (route.settings.name != null) {
      NavigationManager.handleRouteChange(route.settings.name);
    }
  }

  @override
  void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
    super.didPop(route, previousRoute);
    if (previousRoute?.settings.name != null) {
      NavigationManager.handleRouteChange(previousRoute!.settings.name);
    }
  }

  @override
  void didReplace({Route<dynamic>? newRoute, Route<dynamic>? oldRoute}) {
    super.didReplace(newRoute: newRoute, oldRoute: oldRoute);
    if (newRoute?.settings.name != null) {
      NavigationManager.handleRouteChange(newRoute!.settings.name);
    }
  }
}

/// 导航混入 - 为页面提供导航功能
mixin NavigationMixin<T extends StatefulWidget> on State<T> {
  @override
  void initState() {
    super.initState();
    // 页面初始化后检查悬浮播放器显示状态
    WidgetsBinding.instance.addPostFrameCallback((_) {
      NavigationManager.showFloatingPlayerIfNeeded(context);
    });
  }

  /// 导航到音乐搜索页面
  Future<void> toMusicSearch() {
    return NavigationManager.toMusicSearch(context);
  }

  /// 导航到音乐播放页面
  Future<void> toMusicPlayer({dynamic music, bool autoPlay = false}) {
    return NavigationManager.toMusicPlayer(
      context,
      music: music,
      autoPlay: autoPlay,
    );
  }

  /// 导航到播放列表页面
  Future<void> toPlaylist({int initialIndex = 0}) {
    return NavigationManager.toPlaylist(context, initialIndex: initialIndex);
  }

  /// 返回上一页
  void goBack() {
    NavigationManager.back(context);
  }

  /// 返回到首页
  void backToHome() {
    NavigationManager.backToHome(context);
  }
}
